package com.wyl.home

import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.toDisposables
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.ObservableBody
import com.wuhenzhizao.titlebar.widget.CommonTitleBar
import com.wyl.base.*
import com.wyl.base.binding.banner.GlideImageLoad
import com.wyl.base.binding.loadCircleImage
import com.wyl.base.binding.url
import com.wyl.home.databinding.HomeItemBinding
import com.wyl.home.databinding.HomeItemTopBinding
import com.wyl.home.search.SearchActivity
import com.wyl.home.video.VideoListActivity
import com.wyl.libbase.base.NormalActivity
import com.wyl.libbase.extend.dp2px
import com.wyl.libbase.extend.openActivity
import com.wyl.libbase.extend.versionCode
import com.wyl.libbase.utils.KLog
import com.youth.banner.BannerConfig
import kotlinx.android.synthetic.main.home_activity.*
import model.UiConfig
import update.UpdateAppUtils

@Route(path = HomePage)
class HomeActivity : NormalActivity() {
    override fun getLayoutId(): Int = R.layout.home_activity

    override fun initView() {
        titlebar.apply {
            leftImageButton.apply {
                loadCircleImage(ACacheHelper.getUserData().avatar)
                scaleType = ImageView.ScaleType.FIT_XY
                setImageResource(R.drawable.placeholder_circle)
                setPadding(dp2px(4f), dp2px(4f), dp2px(4f), dp2px(4f))
                val params = layoutParams as RelativeLayout.LayoutParams
                params.marginStart = dp2px(10f)
                params.width = dp2px(38f)
                params.height = dp2px(38f)
            }

            centerSearchEditText.hint = "请输入关键词搜索"
            centerSearchRightImageView.visibility = View.GONE
            centerSearchEditText.setOnClickListener { openActivity(SearchActivity::class.java) }

            setListener { _, action, _ ->
                when (action) {
                    CommonTitleBar.ACTION_LEFT_BUTTON -> openActivity(MinePage)
                    CommonTitleBar.ACTION_SEARCH -> openActivity(SearchActivity::class.java)
                    else -> {
                    }
                }
            }

            rightCustomView.findViewById<ImageView>(R.id.iv_history)
                .setOnClickListener { openActivity(VideoHistoryPage) }
            rightCustomView.findViewById<ImageView>(R.id.iv_message)
                .setOnClickListener { openActivity(MessagePage) }
        }

        refreshLayout.apply {
            setEnableLoadmore(false)
            setOnRefreshListener(loadListener)
        }


    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.everyday -> openActivity(VideoListActivity::class.java) { putExtra("title", "每日更新") }
            R.id.hot -> openActivity(VideoListActivity::class.java) { putExtra("title", "人气推荐") }
        }
    }

    override fun refresh() {
        OkGo.post<BaseResponse<List<Map<String, String>>>>(HOME_BANNER)
            .converter(object : JsonConvert<BaseResponse<List<Map<String, String>>>>() {})
            .adapt(ObservableBody<BaseResponse<List<Map<String, String>>>>())
            .doFinally { refreshLayout.finishRefreshing() }
            .map { it.data }
            .subscribe { data ->
                val urls = data.map { it["url"] }
                val ids = data.map { it["appFolkOperaId"] }
                banner.setImages(urls)
                    .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                    .setImageLoader(GlideImageLoad())
                    .setOnBannerListener {
                        ids[it]?.let { id -> openVideoDetailPage(id) }
                    }
                    .start()

            }
            .toDisposables(disposables)

        OkGo.post<BaseResponse<List<Map<String, String>>>>(HOME_EVERY)
            .converter(object : JsonConvert<BaseResponse<List<Map<String, String>>>>() {})
            .adapt(ObservableBody<BaseResponse<List<Map<String, String>>>>())
            .map { it.data }
            .subscribe {
                layoutEveyday.removeAllViews()
                it.forEachIndexed { index, item ->
                    val binding = HomeItemBinding.inflate(layoutInflater, layoutEveyday, true)
                    if (index < it.size - 1) {
                        val params = binding.root.layoutParams as LinearLayout.LayoutParams
                        params.marginEnd = dp2px(14.0f)
                    }
                    binding.item = item
                    binding.root.setOnClickListener {
                        openVideoDetailPage(item["appFolkOperaId"], item["appVideoId"], true)
                    }
                }
            }
            .toDisposables(disposables)

        OkGo.post<BaseResponse<List<Map<String, String>>>>(HOME_HOT)
            .converter(object : JsonConvert<BaseResponse<List<Map<String, String>>>>() {})
            .adapt(ObservableBody<BaseResponse<List<Map<String, String>>>>())
            .map { it.data }
            .subscribe { data ->
                val map = data.groupBy { it["type"] }
                // "type": "2"//类型 2 每日更新上面的视频   3人气推荐
                layout.removeAllViews()
                layoutHot.removeAllViews()
                val timetable = HomeItemTopBinding.inflate(layoutInflater, layout, true)
                (timetable.root.layoutParams as LinearLayout.LayoutParams).marginEnd = dp2px(22.0f)
                timetable.image.setImageResource(R.drawable.icon_timetable)
                timetable.text.text = "时刻表"
                timetable.root.setOnClickListener { openActivity(TimetablePage) }

                val top = map["2"]
                top?.forEachIndexed { index, item ->
                    val binding = HomeItemTopBinding.inflate(layoutInflater, layout, true)
                    if (index < top.size - 1) {
                        val params = binding.root.layoutParams as LinearLayout.LayoutParams
                        params.marginEnd = dp2px(22.0f)
                    }
                    item["appUrl"]?.let {
                        KLog.d("appUrl = $it")
                        binding.image.loadCircleImage(it)
                    }
                    item["operaName"]?.let { binding.text.text = it }
                    binding.root.setOnClickListener { openVideoDetailPage(item["appFolkOperaId"]) }
                }

                val bottom = map["3"]
                bottom?.forEachIndexed { index, item ->
                    val binding = HomeItemBinding.inflate(layoutInflater, layoutHot, true)
                    if (index < bottom.size - 1) {
                        val params = binding.root.layoutParams as LinearLayout.LayoutParams
                        params.marginEnd = dp2px(14.0f)
                    }
                    binding.item = item
                    binding.root.setOnClickListener { openVideoDetailPage(item["appFolkOperaId"]) }
                }
            }
            .toDisposables(disposables)
    }

    override fun loadData() {
        refreshLayout.startRefresh()

        OkGo.post<BaseResponse<Map<String, String>>>(HOME_UPDATE)
            .params("version", versionCode())
            .params("type", "2")
            .converter(object : JsonConvert<BaseResponse<Map<String, String>>>() {})
            .adapt(ObservableBody<BaseResponse<Map<String, String>>>())
            .subscribe {
                if (it.code == 0) {
                    val data = it.data
                    val uiConfig = UiConfig().apply {
                        updateBtnTextColor = resources.getColor(R.color.ui_colorPrimary)
                        cancelBtnText = "下次再说"
                    }

                    UpdateAppUtils.getInstance()
                        .apkUrl(data["url"]?.url().toString())
                        .updateTitle("有新版本了")
                        .updateContent(data["introduce"].toString())
                        .uiConfig(uiConfig)
                        .update()
                }
            }.toDisposables(disposables)
    }

}
